package edu.biwu.cookie05;

import edu.biwu.utils.CookieUtils;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import org.w3c.dom.CDATASection;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@WebServlet("/lastVisited")
public class LastVisited extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        Cookie[] cookies = request.getCookies();
        Cookie cookie = CookieUtils.getCookie(cookies, "lastVisited");

        if (cookie == null) {
            response.getWriter().write("欢迎第一次访问");
        }else {
            //说明首次访问，创建一个lastVisitedCookie记录当前访问时间
            //取出cookie中记录的时间，响应给浏览器
            String datestr = cookie.getValue();

            //对datestr进行解码，编码出原始值
            String decodeDate = URLDecoder.decode(datestr, "utf-8");
            response.getWriter().write("您上次访问时间：" + decodeDate);
        }
        //无论第一次访问呢，还是第二次，第三次，....,第n次访问，都需要将当前系统时间设置到cookie中,响应给浏览器
        String formatDate = DateTimeFormatter.ofPattern("yyy-MM-dd HH:mm:ss").format(LocalDateTime.now());

        //再将日期放入cookie前，先进行编码，防止cookie不支持某些字符
        String encodeDate = URLEncoder.encode(formatDate, "UTF-8");

        Cookie lastVisitedCookie = new Cookie("lastVisited",encodeDate);
        lastVisitedCookie.setMaxAge(7*24*60*60);
        lastVisitedCookie.setPath(request.getContextPath());
        response.addCookie(lastVisitedCookie);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
